package com.bw.documents.preview

import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_documents.databinding.ActivityPdfBinding
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL


@Route(path = "/documents/PDFActivity")
class PDFActivity : AppCompatActivity(), OnLoadCompleteListener, OnPageChangeListener {

    public val v : ActivityPdfBinding by lazy { ActivityPdfBinding.inflate(LayoutInflater.from(this)) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(v.root)
        val path = intent.extras!!.getString("path")
        v.pdfPage.backImg.setOnClickListener { finish() }
        v.pdfPage.titleTv.text = "PDF预览"
        RetrievePDFStream().execute(path)


    }
    inner class RetrievePDFStream : AsyncTask<String?, Void?, InputStream?>() {
         override fun doInBackground(vararg strings: String?): InputStream? {
            var inputStream: InputStream? = null
            try {
                val url = URL(strings[0])
                val urlConnection: HttpURLConnection = url.openConnection() as HttpURLConnection
                if (urlConnection.getResponseCode() === 200) {
                    inputStream = BufferedInputStream(urlConnection.getInputStream())
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return inputStream
        }

         override fun onPostExecute(inputStream: InputStream?) {
            v.pdfView.fromStream(inputStream)
                .defaultPage(0)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onLoad(this@PDFActivity)
                .onPageChange(this@PDFActivity)
                .scrollHandle(DefaultScrollHandle(this@PDFActivity))
                .load()
        }
    }

    override fun loadComplete(nbPages: Int) {
        // PDF加载完成的回调方法
    }

    override fun onPageChanged(page: Int, pageCount: Int) {
        // 页面切换的回调方法
    }

}